<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <title>流程模型</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <jsp:include page="/inc/head.jsp" flush="true"/>
    <jsp:include page="/inc/footer.jsp" flush="true"/>
    <script src="${basePath }/js/tip.js"></script>
    <style>
        .content .box {
            border-top: 0;
        }
        .content .bootstrap-table .fixed-table-toolbar .icon-refresh {
            padding: 3px 0;
        }
        .fixed-table-toolbar .bs-bars, .fixed-table-toolbar .columns, .fixed-table-toolbar .search {
            margin-top: 0;
        }
    </style>
</head>

<body class="hold-transition skin-blue sidebar-mini" style="overflow:hidden;">
<!-- Main content -->
<section class="content">
    <div id="toolbar" class="btn-group">
        <shiro:hasPermission name="upms:model:create">
        <button id="btn_add" type="button" class="btn btn-default" onclick="addModel()">
            <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>创建模型
        </button>
        </shiro:hasPermission>
        <shiro:hasPermission name="upms:model:update">
        <button id="btn_update" type="button" class="btn btn-default" onclick="updateModel()">
            <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改模型
        </button>
        </shiro:hasPermission>
        <shiro:hasPermission name="upms:model:delete">
        <button id="btn_delete" type="button" class="btn btn-default" onClick ="delModel()">
            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除模型
        </button>
        </shiro:hasPermission>
        <shiro:hasPermission name="upms:model:deploy">
        <button id="btn_import" type="button" class="btn btn-default" onClick ="deployModel()">
            <span class="glyphicon glyphicon-wrench" aria-hidden="true"></span>部署模型
        </button>
        </shiro:hasPermission>
    </div>

    <div id = "rowTable" class="row">
        <div class="col-xs-12">
            <div class="box">
                <div class="box-body table-responsive no-padding">
                    <table id="modelTable"></table>
                </div>
            </div>
        </div>
    </div>

    <div id="addActModel" class="modal fade bs-example-modal-lg addUpdateInfo" role="dialog" aria-labelledby="myLargeModalLabel">
        <div class="modal-dialog " role="document">
            <div class="modal-content" style="width: 600px;">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="exampleModalLabel" >新增模型</h4>
                </div>
                <div class="modal-body" style="height: 300px;">
                    <form id="createModelForm" method="post">
                        <div class="form-group">
                            <label for="name">名称</label>
                            <input id="name" type="text" class="form-control" name="name" maxlength="20">
                        </div>
                        <div class="form-group">
                            <label for="name">key</label>
                            <input id="key" type="text" class="form-control" name="key" maxlength="20">
                        </div>
                        <div class="form-group">
                            <label for="description">描述</label>
                            <input id="description" type="text" class="form-control" name="description" maxlength="300">
                        </div>
                    </form>
                </div>
                <div class="modal-footer bg-info">
                    <button type="button" class="btn green" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="searchFile" onclick="createSubmit(this);">确认</button>
                </div>
            </div>
        </div>
    </div>
</section>
<script type="text/javascript">
    var $table = $('#modelTable');
    $(function(){
        showTable();
    })
    /**
     * 显示table表单内容
     */
    function showTable() {
        $table.bootstrapTable({
            url: BASE_PATH+"/pcwindow/getActModel",
//                height: getHeight(),
            striped: true,
//            search: true,
            showRefresh: true,
            showColumns: true,
            minimumCountColumns: 2,
            clickToSelect: true,
            detailView: false,
            detailFormatter: 'detailFormatter',
            pagination: true,
            paginationLoop: false,
            sidePagination: 'server',
            silentSort: false,
            smartDisplay: false,
            escape: true,
            searchOnEnterKey: true,
            idField: 'id',
            maintainSelected: true,
            toolbar: '#toolbar',
            columns: [
                {field: 'ck', align: 'center', checkbox: true},
                {field: 'id', visible:false},
                {field: 'key', title: 'KEY',  align: 'center'},
                {field: 'name', title: 'name', align: 'center'},
                {field: 'version', title: 'Version', align: 'center'},
                {field: 'createTime', title: '创建时间', align: 'center', formatter:"formatCT"},
                {field: 'lastUpdateTime', title: '最后更新时间', align: 'center', formatter:"formatLUT"},
                {field: 'metaInfo', title: '元数据', align: 'center'},
                {field: 'export', title: '导出', align: 'center', formatter:"formatExport"},
                {field: 'action', title: '操作', align: 'center', formatter: 'actionFormatter', events: 'actionEvents', clickToSelect: false}
            ],
            onLoadSuccess:function(data){
                //无数据隐藏分页
                if(data && data.total == 0){
                    $('.fixed-table-pagination').hide()
                }
            }
        });
        $table.bootstrapTable('resetView',{height:setHeight()});
    }
    //将创建时间转换
    function formatCT(value, row, index){
        return formatDateTime(value);
    }
    //将创建时间转换
    function formatLUT(value, row, index){
        return formatDateTime(value);
    }
    //导出动作
    function formatExport(value, row, index){
        return [
            '<a href="${basePath}/pcwindow/export/'+row.id+'/bpmn" target="_blank" style="color:blue">BPMN</a>/',
            '<a href="${basePath}/pcwindow/export/'+row.id+'/json" target="_blank" style="color:blue">JSON</a>/',
            '<a href="javascript:;" onclick="showSvgTip();" style="color:blue">SVG</a>'
        ].join("");
    }
    //SVG
    function actionFormatter(value, row, index) {
        return [
            '<shiro:hasPermission name="upms:model:update"><a class="update" href="javascript:;" onclick="updateModel(' + row.id +')" data-toggle="tooltip" title="Edit"><i class="glyphicon glyphicon-edit"></i></a> </shiro:hasPermission>　',
            '<shiro:hasPermission name="upms:model:deploy"><a class="deploy" href="javascript:;" onclick="deployModel(' + row.id +')" data-toggle="tooltip" title="Deploy"><i class="glyphicon glyphicon-wrench"></i></a> </shiro:hasPermission>',
            '<shiro:hasPermission name="upms:model:delete"><a class="delete" href="javascript:;" onclick="delModel(' + row.id +')" data-toggle="tooltip" title="Remove"><i class="glyphicon glyphicon-remove"></i></a>  </shiro:hasPermission> '
        ].join('');
    }
    //操作初始化
    function showSvgTip() {
        confirmEvent('点击"编辑"链接,在打开的页面中打开控制台执行\njQuery(".ORYX_Editor *").filter("svg")\n即可看到svg标签的内容.');
    }

    //创建模型
    function addModel() {
        //清楚模型中的数据
        $("#createModelForm")[0].reset();
        // 加载addmodel
        $('#addActModel').modal({
            keyboard: true
        });
    }

    //创建提交
    function createSubmit(evn) {
        $(evn).attr("disabled",true);
        var name = $("#name").val();
        if(!name){
            confirmEvent("请填写名称");
            $(evn).attr("disabled",false);
            return;
        }
        $.ajax({
            type: 'post',
            url: '${basePath}/pcwindow/createModel',
            data: $('#createModelForm').serialize(),
            success: function(data) {
                var status = data.status;
                if(status==0){
                    confirmEvent(data.msg);
                }else{
                    window.open("${basePath}/modeler.html?modelId="+data.data);
                    $('#addActModel').modal("hide")
                    $table.bootstrapTable('refresh');
                }
                $(evn).attr("disabled",false);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                confirmEvent('系统开小差了，请稍后再试!');
                $(evn).attr("disabled",false);
            }
        });
    }

    //编辑模型
    function updateModel(id){
        var flag = false;
        var rows = $table.bootstrapTable('getSelections');
        if(id==null||typeof(id)=="undefined"){
            if (rows.length != 1) {
                confirmEvent('请仅且选择一条记录');
            }else{
                id = rows[0].id;
                flag = true;
            }
        }else{
            flag = true;
        }
        if(flag){
            window.open("${basePath}/modeler.html?modelId="+id);
        }
    }

    //删除模型
    function delModel(id){
        var ids = [];
        var flag = false;
        var rows = $table.bootstrapTable('getSelections');
        if(id==null||typeof(id)=="undefined"){
            if (rows.length == 0) {
                confirmEvent('请至少选择一条记录!');
            }else{
                for (var i in rows) {
                    ids.push(rows[i].id);
                }
                flag = true;
            }
        }else{
            ids.push(id);
            flag = true;
        }
        if(flag){
            $.ajax({
                type: 'get',
                url: '${basePath}/pcwindow/delModel/' + ids.join("-"),
                success: function(result) {
                    if (result.state == 0) {
                        confirmEvent('删除失败！');
                        $table.bootstrapTable('refresh');
                    } else {
                        confirmEvent('删除成功！');
                        $table.bootstrapTable('refresh');
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    confirmEvent('系统开小差了，请稍后再试!');
                }
            });
        }
    }

    //部署模型
    function deployModel(id){
        var ids = [];
        var flag = false;
        var rows = $table.bootstrapTable('getSelections');
        if(id==null||typeof(id)=="undefined"){
            if (rows.length == 0) {
                confirmEvent('请至少选择一条记录！');
            }else{
                for (var i in rows) {
                    ids.push(rows[i].id);
                }
                flag = true;
            }
        }else{
            ids.push(id);
            flag = true;
        }
        if(flag){
            $.ajax({
                url:"${basePath}/pcwindow/deploy/" + ids.join("-"),
                type:"get",
                dataType:'json',
                success:function(data){
                    if(data.length==0){
                        confirmEvent("部署成功!");
                    }else{
                        confirmEvent("部署失败!");
                    }
                },
                error:function(XMLHttpRequest, textStatus, errorThrown) {
                    confirmEvent('系统开小差了，请稍后再试!');
                }
            })
        }
    }
    /**
     * 表格高度自适应
     * @return
     * winTop 浏览器视口高度
     * header 顶部通栏
     * breadcrumb 面包屑
     * mainFooter 底部
     */
    function setHeight(){
        var winTop = $(window.top).height(),
            header = window.top.document.querySelector('.main-header').offsetHeight,
            breadcrumb =  window.top.document.querySelector('.breadcrumb').offsetHeight,
            mainFooter = window.top.document.querySelector('.main-footer').offsetHeight;
        return winTop-header-breadcrumb-mainFooter-10;
    }
</script>
</body>
</html>